package handler

import (
	"context"
	"go_final/mxshop_srvs/goods_srv/global"
	"go_final/mxshop_srvs/goods_srv/model"
	goodspb "go_final/mxshop_srvs/goods_srv/proto/protofile"

	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"gorm.io/gorm"

	"google.golang.org/protobuf/types/known/emptypb"
)

// CategoryBrandList 获取分类品牌列表
func (s Server) CategoryBrandList(c context.Context, request *goodspb.CategoryBrandFilterRequest) (*goodspb.
	CategoryBrandListResponse, error) {
	var categoryBrands []model.GoodsCategoryBrand
	res := global.DB.Preload("Brand").Preload("Category").Scopes(Paginate(int(request.Pages), int(request.PagePerNums))).Find(
		&categoryBrands)
	if res.Error != nil && res.Error != gorm.ErrRecordNotFound {
		return nil, status.Error(codes.Internal, res.Error.Error())
	}

	rsp := goodspb.CategoryBrandListResponse{}

	// 查询总条数
	var count int64
	res = global.DB.Model(&model.GoodsCategoryBrand{}).Count(&count)
	rsp.Total = int32(count)

	for _, categoryBrand := range categoryBrands {
		rsp.Data = append(rsp.Data, &goodspb.CategoryBrandResponse{
			Id: categoryBrand.ID,
			Brand: &goodspb.BrandInfoResponse{
				Id:   categoryBrand.BrandID,
				Name: categoryBrand.Brand.Name,
				Logo: categoryBrand.Brand.Logo,
			},
			Category: &goodspb.CategoryInfoResponse{
				Id:             categoryBrand.CategoryID,
				Name:           categoryBrand.Category.Name,
				ParentCategory: categoryBrand.Category.ParentCategoryID,
				Level:          categoryBrand.Category.Level,
				IsTab:          categoryBrand.Category.IsTap,
			},
		})
	}

	return &rsp, nil
}

// GetCategoryBrandList 通过分类查询品牌
func (s Server) GetCategoryBrandList(c context.Context, request *goodspb.CategoryInfoRequest) (*goodspb.
	BrandListResponse, error) {
	var category model.Category
	res := global.DB.First(&category, request.Id)
	if res.Error != nil && res.Error != gorm.ErrRecordNotFound {
		return nil, status.Error(codes.Internal, res.Error.Error())
	}

	if res.RowsAffected == 0 {
		return nil, status.Error(codes.NotFound, "该分类不存在")
	}

	/// 查找该分类拥有的品牌(需要预加载Brand字段)
	var categoryBrands []model.GoodsCategoryBrand
	res = global.DB.Preload("Brand").Where(&model.GoodsCategoryBrand{
		CategoryID: category.ID,
	}).Find(&categoryBrands)

	if res.Error != nil && res.Error != gorm.ErrRecordNotFound {
		return nil, status.Error(codes.Internal, res.Error.Error())
	}

	var rsp goodspb.BrandListResponse
	rsp.Total = int32(res.RowsAffected)
	for _, categoryBrand := range categoryBrands {
		rsp.Data = append(rsp.Data, &goodspb.BrandInfoResponse{
			Id:   categoryBrand.BrandID,
			Name: categoryBrand.Brand.Name,
			Logo: categoryBrand.Brand.Logo,
		})
	}

	return &rsp, nil
}

func (s Server) CreateCategoryBrand(c context.Context, request *goodspb.CategoryBrandRequest) (*goodspb.
	CategoryBrandResponse, error) {
	var category model.Category
	res := global.DB.First(&category, request.CategoryId)
	if res.Error != nil && res.Error != gorm.ErrRecordNotFound {
		return nil, status.Error(codes.Internal, res.Error.Error())
	}

	if res.RowsAffected == 0 {
		return nil, status.Error(codes.NotFound, "没有该分类")
	}

	var brand model.Brand
	res = global.DB.First(&brand, request.BrandId)
	if res.Error != nil && res.Error != gorm.ErrRecordNotFound {
		return nil, status.Error(codes.Internal, res.Error.Error())
	}

	if res.RowsAffected == 0 {
		return nil, status.Error(codes.NotFound, "没有该品牌")
	}

	// 开始创建分类品牌(品牌id和分类id创建了联合唯一索引, 所以不需要查重)
	categoryBrand := model.GoodsCategoryBrand{
		CategoryID: request.CategoryId,
		BrandID:    request.BrandId,
	}

	res = global.DB.Save(&categoryBrand)
	if res.Error != nil && res.Error != gorm.ErrRecordNotFound {
		return nil, status.Error(codes.Internal, res.Error.Error())
	}

	return &goodspb.CategoryBrandResponse{
		Id: categoryBrand.CategoryID,
	}, nil
}

func (s Server) DeleteCategoryBrand(c context.Context, request *goodspb.CategoryBrandRequest) (*emptypb.Empty, error) {
	res := global.DB.Delete(&model.GoodsCategoryBrand{}, request.Id)

	if res.Error != nil && res.Error != gorm.ErrRecordNotFound {
		return nil, status.Error(codes.Internal, res.Error.Error())
	}

	if res.RowsAffected == 0 {
		return nil, status.Errorf(codes.NotFound, "品牌分类不存在")
	}

	return &emptypb.Empty{}, nil
}

func (s Server) UpdateCategoryBrand(c context.Context, request *goodspb.CategoryBrandRequest) (*emptypb.Empty, error) {
	var category model.Category
	res := global.DB.First(&category, request.CategoryId)
	if res.Error != nil && res.Error != gorm.ErrRecordNotFound {
		return nil, status.Error(codes.Internal, res.Error.Error())
	}

	if res.RowsAffected == 0 {
		return nil, status.Error(codes.NotFound, "没有该分类")
	}

	var brand model.Brand
	res = global.DB.First(&brand, request.BrandId)
	if res.Error != nil && res.Error != gorm.ErrRecordNotFound {
		return nil, status.Error(codes.Internal, res.Error.Error())
	}

	if res.RowsAffected == 0 {
		return nil, status.Error(codes.NotFound, "没有该品牌")
	}

	categoryBrand := model.GoodsCategoryBrand{
		CategoryID: request.CategoryId,
		BrandID:    request.BrandId,
	}

	res = global.DB.Model(model.GoodsCategoryBrand{
		BaseModel: model.BaseModel{
			ID: request.Id,
		},
	}).Updates(&categoryBrand)

	if res.Error != nil && res.Error != gorm.ErrRecordNotFound {
		return nil, status.Error(codes.Internal, res.Error.Error())
	}

	return &emptypb.Empty{}, nil
}
